package com.lerays.spider.sougou.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * basic encryption class
 * 
 * @author chenxin<chenxin619315@gmail.com>
 */
public class Encryption 
{
	private static final char[] hexDigits = {
		'0', '1', '2', '3', '4', '5', '6', '7', 
		'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
	};
	
	/**
	 * convert the bytes to the hex string
	 * 
	 * @param	bytes
	 * @return	String
	 */
	public static String byte2HexString( byte[] bytes )
	{
		int len = bytes.length;
		StringBuilder sb = new StringBuilder(len * 2);
		
		for ( int i = 0; i < len; i++ )
		{
			sb.append(hexDigits[(bytes[i] >> 4) & 0x0F])
			  .append(hexDigits[(bytes[i]) & 0x0F]);
		}
		
		return sb.toString();
	}
	
	/**
	 * encrypt the specifield string
	 * 
	 * @param	str
	 * @param	algorithm
	 */
	public static String encrypt( String str, String algorithm )
	{
		String ret = null;
		
		try {
			MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
			messageDigest.update(str.getBytes());
			ret = byte2HexString(messageDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			//e.printStackTrace();
		}
		
		return ret;
	}
}
